<script setup lang="ts">
import { useMessage, NSpace, NDataTable, NModal, NButton } from 'naive-ui'
import { ChevronLeft12Filled, ChevronRight12Filled } from '@vicons/fluent'
import { format, subDays, addDays } from 'date-fns'
import { ref, watch, h, defineComponent } from 'vue'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import ArrangementUpdate from './components/ArrangementUpdate.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const message = useMessage()
const route = useRoute()
const tableLoading = ref(false)

//日期
const startData: any = ref()
const endData: any = ref()
startData.value = format(beginOfWeek(new Date()), 'yyyy-MM-dd')
endData.value = format(endOfWeek(new Date()), 'yyyy-MM-dd')

function beginOfWeek(dateValue: any) {
  let date
  if (dateValue instanceof Date) {
    date = dateValue
  } else {
    date = new Date(dateValue)
  }
  let subDay = 0
  let weekDay = date.getDay()
  if (weekDay == 0) {
    //周天
    subDay = 6
  } else {
    subDay = weekDay - 1
  }
  let beginDateTime = date.getTime() - 86400000 * subDay
  return new Date(beginDateTime)
}

//获取日期周结束日期（周一为每周的开始，周日为每周的结束）
function endOfWeek(dateValue: any) {
  let date
  if (dateValue instanceof Date) {
    date = dateValue
  } else {
    date = new Date(dateValue)
  }
  let weekDay = date.getDay()
  if (weekDay == 0) {
    //周天
    return date
  } else {
    let addDay = 7 - weekDay
    let endDateTime = date.getTime() + 86400000 * addDay
    return new Date(endDateTime)
  }
}

const subWeek = () => {
  startData.value = format(subDays(new Date(startData.value), 7), 'yyyy-MM-dd')
  endData.value = format(subDays(new Date(endData.value), 7), 'yyyy-MM-dd')
  queryTableData()
}
const addWeek = () => {
  startData.value = format(addDays(new Date(startData.value), 7), 'yyyy-MM-dd')
  endData.value = format(addDays(new Date(endData.value), 7), 'yyyy-MM-dd')
  queryTableData()
}

//表格数据
const InfoData: any = ref([])
const columnsCopy: any = ref([])
const leaderId = ref()
const queryTableData = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'selfDesktop',
    api: 'leadList',
    override: {
      params: {
        startTime: startData.value,
        endTime: endData.value
      }
    }
  })
  if (error) return message.error(error.message)
  InfoData.value = res.data?.list
  const tmpName: any = res.data?.nameList.length
  columnsCopy.value = [
    {
      title: '',
      key: 'week',
      width: '100rem',
      align: 'center',
      render(e: any) {
        const { workTime, week } = e
        return h(
          NSpace,
          {
            inline: true,
            vertical: true,
            style: 'line-height: 1'
          },
          {
            default: () => [h('span', null, week), h('span', null, `（${workTime.slice(5)}）`)]
          }
        )
      }
    },
    {
      title: res.data?.nameList[0],
      key: 'workPlan1',
      width: '500rem',
      align: 'center',
      cellProps: (e: any) => ({
        style: {
          backgroundColor: '#d9e6d9',
          borderRight: '1px solid #ffffff',
          textAlign: 'left',
          FontFamily: '仿宋_GB2312'
        },
        onClick: () => {
          addPlanVisible.value = true
          workTime.value = {
            all: e,
            workTime: e.workTime,
            modal: e?.workPlan1 ? (e?.workPlan1.indexOf('下午') != -1 ? 1 : 0) : 0,
            workPlan: e.workPlan1
          }
          leaderId.value = res.data?.userIdList[0]
        }
      }),
      render: (e: any) =>
        e?.workPlan1 ? (e?.workPlan1.indexOf('下午') != -1 ? toBr(e?.workPlan1) : e?.workPlan1) : ''
    },
    {
      title: res.data?.nameList[1],
      key: 'workPlan2',
      width: '500rem',
      align: 'center',
      cellProps: (e: any) => ({
        style: {
          backgroundColor: '#d9e6d9',
          borderRight: '1px solid #ffffff',
          textAlign: 'left',
          FontFamily: '仿宋_GB2312'
        },
        onClick: () => {
          addPlanVisible.value = true
          workTime.value = {
            all: e,
            workTime: e.workTime,
            modal: e?.workPlan2 ? (e?.workPlan2.indexOf('下午') != -1 ? 1 : 0) : 0,
            workPlan: e.workPlan2
          }
          leaderId.value = res.data?.userIdList[1]
        }
      }),
      render: (e: any) =>
        e?.workPlan2 ? (e?.workPlan2.indexOf('下午') != -1 ? toBr(e?.workPlan2) : e?.workPlan2) : ''
    },
    {
      title: res.data?.nameList[2],
      key: 'workPlan3',
      width: '500rem',
      align: 'center',
      cellProps: (e: any) => ({
        style: {
          backgroundColor: '#d9e6d9',
          textAlign: 'left',
          FontFamily: '仿宋_GB2312'
        },
        onClick: () => {
          addPlanVisible.value = true
          workTime.value = {
            all: e,
            workTime: e.workTime,
            modal: e?.workPlan3 ? (e?.workPlan3.indexOf('下午') != -1 ? 1 : 0) : 0,
            workPlan: e.workPlan3
          }
          leaderId.value = res.data?.userIdList[2]
        }
      }),
      render: (e: any) =>
        e?.workPlan3 ? (e?.workPlan3.indexOf('下午') != -1 ? toBr(e?.workPlan3) : e?.workPlan3) : ''
    }
  ]
  columnsCopy.value = columnsCopy.value.slice(0, tmpName + 1)
  tableLoading.value = false
}

const PlanContent = defineComponent({
  render() {
    return h('div', {
      class: 'planContent'
    }, this.$slots.default?.())
  }
})

//上下午工作安排分开
const toBr = (val: any) => {
  const tmp: any = val?.split('下午:')
  return h(
    'div',
    {},
    {
      default: () => [
        h(PlanContent, {
          style: {
            display: tmp[0]?.replace('上午:', '') ? 'block' : 'none'
          },
          "data-desc": "· 上午："
        }, { default: () => tmp[0]?.replace('上午:', '') ? tmp[0].replace('上午:', '') : '' }),
        h(PlanContent,
          {
            style: {
              display: tmp[1]?.replace('下午:', '') ? 'block' : 'none'
            },
            "data-desc": "· 下午："
          }
          , {
            default: () => tmp[1]?.replace('下午:', '') ? tmp[1] : ''
          })
      ]
    }
  )
}
//编辑弹窗
const addPlanVisible: any = ref(false)
const workTime = ref()

//发布
const sendLoading = ref(false)
const sendVisiable = ref(false)
const handleSend = () => {
  sendLoading.value = true
  sendVisiable.value = true
}

const againSend = async () => {
  const [error, res] = await sendRequest({
    module: 'selfDesktop',
    api: 'leadSend',
    override: {
      params: {
        startTime: startData.value,
        endTime: endData.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code != 0) message.error(res.msg)
  message.success(res.msg)
  sendVisiable.value = false
  sendLoading.value = false
  queryTableData()
}
//导出
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '.docx'
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const exportLoading = ref(false)
async function handleExport() {
  exportLoading.value = true
  const [error, data, headers] = await sendRequest({
    module: 'selfDesktop',
    api: 'leadExport',
    override: {
      data: {
        startTime: startData.value,
        endTime: endData.value
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, data, '馆领导一周工作安排')
  exportLoading.value = false
}

watch(
  () => route.path,
  () => {
    if (route.path == '/leaderArrangement' && startData && endData) queryTableData()
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <div class="content">
    <NSpace justify="space-between">
      <NSpace justify="start">
        <div class="toptitle">馆领导一周工作安排</div>
        <NButton type="primary" style="width: 80rem" @click="handleSend" :loading="sendLoading" ghost>
          发布
        </NButton>
        <NButton ghost type="primary" style="width: 80rem" @click="handleExport" :loading="exportLoading">
          导出
        </NButton>
      </NSpace>
      <NSpace justify="end">
        <div class="title_left" @click="subWeek()">
          <ChevronLeft12Filled />
        </div>
        <div class="title_middle">{{ startData }}至{{ endData }}</div>
        <div class="title_right" @click="addWeek()">
          <ChevronRight12Filled />
        </div>
      </NSpace>
    </NSpace>
    <NDataTable :loading="tableLoading" :bordered="false" :columns="columnsCopy" :data="InfoData" min-height="640rem"
      flex-height style="flex: 1; --n-td-padding: 10rem; margin-top: 10rem" />
  </div>

  <NModal :auto-focus="false" v-model:show="addPlanVisible">
    <ArrangementUpdate @update="queryTableData" :value="workTime" :leaderId="leaderId"
      @close="addPlanVisible = false" />
  </NModal>

  <NModal :auto-focus="false" v-model:show="sendVisiable">
    <VDialogContent @close="; (sendVisiable = false), (sendLoading = false)" @submit="againSend" title="发布提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要发布吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style>
.planContent {
  position: relative;
  padding-left: 50px;
}

.planContent::before {
  content: attr(data-desc);
  position: absolute;
  left: 0;
}
</style>

<style scoped lang="scss">
.content {
  width: 100%;
  height: 100%;
  padding: 29px 30px 42px;
}

.toptitle {
  font-size: 22rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  color: #5fb17f;
}

.title_middle {
  border-radius: 3px;
  width: 220rem;
  height: 36rem;
  line-height: 36rem;
  font-size: 14rem;
  color: #5fb17f;
  text-align: center;
  border: 1px solid #5fb17f;
}

.title_left {
  position: relative;
  border: 1px solid #5fb17f;
  border-radius: 3px;
  width: 15rem;
  height: 36rem;
  line-height: 36rem;
  color: #5fb17f;
  text-align: center;
  cursor: pointer;
}

.title_right {
  position: relative;
  border: 1px solid #5fb17f;
  border-radius: 3px;
  width: 15rem;
  height: 36rem;
  line-height: 36rem;
  color: #5fb17f;
  text-align: center;
  cursor: pointer;

  .logo {
    position: absolute;
    margin-left: 3rem;
  }
}

.fontCenter {
  text-align: center;
  height: 100rem;
  line-height: 100rem;
}

.weekCenter {
  text-align: center;
  padding: 35rem;
}

:deep(.n-data-table .n-data-table-tr) {
  height: 100rem;
  background-color: #5fb17f;
}
</style>
